package com.cmc.cloud.cmclink.doc.service.impl.si;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmc.cloud.cmclink.doc.api.document.emums.SiValidEnum;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.BlnoCargoErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.BlnoErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.convert.BlnoCargoConvert;
import com.cmc.cloud.cmclink.doc.entity.BlnoCargoDO;
import com.cmc.cloud.cmclink.doc.entity.BlnoDO;
import com.cmc.cloud.cmclink.doc.mapper.BlnoCargoMapper;
import com.cmc.cloud.cmclink.doc.mapper.BlnoMapper;
import com.cmc.cloud.cmclink.doc.service.si.BlnoCargoService;
import com.cmc.cloud.cmclink.doc.vo.blnocargovo.BlnoCargoCreateReqVO;
import com.cmc.cloud.cmclink.doc.vo.blnocargovo.BlnoCargoPageReqVO;
import com.cmc.cloud.cmclink.doc.vo.blnocargovo.BlnoCargoUpdateReqVO;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 提单货物信息 Service 实现类
 *
 * @author 集运管理员
 */
@Service
@Validated
public class BlnoCargoServiceImpl implements BlnoCargoService {

    @Resource
    private BlnoCargoMapper blnoCargoMapper;
    @Resource
    private BlnoMapper blnoMapper;

    @Override
    public void createBlnoCargo(BlnoCargoCreateReqVO createReqVO) {
        // 插入
        BlnoCargoDO blnoCargo = BlnoCargoConvert.INSTANCE.convert(createReqVO);
        blnoCargoMapper.insert(blnoCargo);
    }

    @Override
    public void updateBlnoCargo(BlnoCargoUpdateReqVO updateReqVO) {
        // 校验存在
        validateBlnoCargoExists(updateReqVO.getId());
        // 更新
        BlnoCargoDO updateObj = BlnoCargoConvert.INSTANCE.convert(updateReqVO);
        blnoCargoMapper.updateById(updateObj);
    }

    @Override
    public void deleteBlnoCargo(Long id) {
        // 校验存在
        validateBlnoCargoExists(id);
        // 删除
        blnoCargoMapper.deleteById(id);
    }
    @Override
    public void deleteBlnoCargoByBlnoId(Long blnoId) {
        LambdaQueryWrapper<BlnoCargoDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlnoCargoDO::getBlnoId, blnoId);
        blnoCargoMapper.delete(queryWrapper);
    }

    private void validateBlnoCargoExists(Long id) {
        if (blnoCargoMapper.selectById(id) == null) {
            throw ServiceExceptionUtil.exception(BlnoCargoErrorCodeConstants.BLNO_CARGO_NOT_EXISTS);
        }
    }

    @Override
    public BlnoCargoDO getBlnoCargo(Long id) {
        return blnoCargoMapper.selectById(id);
    }

    @Override
    public List<BlnoCargoDO> getBlnoCargoByBlnoId(Long blnoId) {
        LambdaQueryWrapper<BlnoCargoDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlnoCargoDO::getBlnoId, blnoId);
        queryWrapper.orderByAsc(BlnoCargoDO::getId);
        return blnoCargoMapper.selectList(queryWrapper);
    }

    @Override
    public List<BlnoCargoDO> getBlnoCargoByBlnoIds(Collection<Long> ids) {
        LambdaQueryWrapperX<BlnoCargoDO> queryWrapperX = new LambdaQueryWrapperX<>();
        queryWrapperX.in(BlnoCargoDO::getBlnoId, ids);
        return blnoCargoMapper.selectList(queryWrapperX);
    }

    @Override
    public List<BlnoCargoDO> getBlnoCargoList(Collection<Long> ids) {
        return blnoCargoMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<BlnoCargoDO> getBlnoCargoPage(BlnoCargoPageReqVO reqVO) {
        IPage<BlnoCargoDO> page = Page.of(reqVO.getPageNo(), reqVO.getPageSize());

        IPage<BlnoCargoDO> result = blnoCargoMapper.selectPageList(page, reqVO);
        return new PageResult<BlnoCargoDO>(result.getRecords(), result.getTotal());
    }

    @Override
    public void createOrUpdateAndDeleteBatch(Long blnoId, List<BlnoCargoUpdateReqVO> newList,
        List<BlnoCargoUpdateReqVO> oldList) {
        // 无效数据直接返回
        if (CollectionUtil.isEmpty(newList) && CollectionUtil.isEmpty(oldList)) {
            return;
        }
        // 默认值
        if (CollectionUtil.isEmpty(newList)) {
            newList = new ArrayList<>();
        }
        if (CollectionUtil.isEmpty(oldList)) {
            oldList = new ArrayList<>();
        }
        List<BlnoCargoUpdateReqVO> createList = new ArrayList<>();
        List<BlnoCargoUpdateReqVO> updateList = new ArrayList<>();
        // 历史数据
        Set<Long> oldIds = oldList.stream().map(e -> e.getId()).collect(Collectors.toSet());
        newList.forEach(e -> {
            if (e.getId() != null) {
                if (oldIds.contains(e.getId())) {
                    // 正常更新
                    updateList.add(e);
                    oldIds.remove(e.getId()); // 剩下的数据需要删除
                } else {
                    // 数据更新非法
                    throw ServiceExceptionUtil.exception(BlnoErrorCodeConstants.SI_NI_UPDATE);
                }
            } else {
                e.setBlnoId(blnoId);
                createList.add(e);
            }
        });
        if (CollectionUtil.isNotEmpty(oldIds)) {
            // 没有匹配上的就是前端删除的
            blnoCargoMapper.deleteBatchIds(oldIds);
        }
        if (CollectionUtil.isNotEmpty(createList)) {
            List<BlnoCargoDO> cargoCreateList = BeanUtil.copyToList(createList, BlnoCargoDO.class);
            blnoCargoMapper.insertBatch(cargoCreateList);
        }
        if (CollectionUtil.isNotEmpty(updateList)) {
            List<BlnoCargoDO> cargoUpdateList = BeanUtil.copyToList(updateList, BlnoCargoDO.class);
            blnoCargoMapper.updateBatch(cargoUpdateList);
        }
    }

    @Override
    public List<BlnoCargoDO> getCargoByBlNo(String blNo) {
        LambdaQueryWrapper<BlnoDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlnoDO::getBlNo, blNo).eq(BlnoDO::getValid, SiValidEnum.VALID.getValue());
        BlnoDO blnoDO = blnoMapper.selectOne(queryWrapper);
        if (blnoDO == null) {
            throw ServiceExceptionUtil.exception(BlnoErrorCodeConstants.BLNO_NOT_EXISTS);
        }
        LambdaQueryWrapper<BlnoCargoDO> cargoQueryWrapper = new LambdaQueryWrapper<>();
        cargoQueryWrapper.eq(BlnoCargoDO::getBlnoId, blnoDO.getId());
        cargoQueryWrapper.orderByAsc(BlnoCargoDO::getId);
        return blnoCargoMapper.selectList(cargoQueryWrapper);
    }
}
